using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class AnyQueryResult<TSource> : ObservableSingleQueryResultBase<bool, TSource>
	{
		readonly Func<TSource, bool> _predicate;
		public AnyQueryResult(IEnumerable<TSource> source, Func<TSource, bool> predicate) : base(source)
		{
			_predicate = predicate;
			OnSourceReset();
		}

		bool _value;

		protected override void OnSourceReset()
		{
			foreach (var item in _attached)
			{
				DetachItem(item);
			}
			_attached.Clear();
			foreach (var item in _source)
			{
				AttachItem(item);
			}
			_value = false;
			foreach (var item in _source)
			{
				if (_predicate(item))
				{
					_value = true;
					break;
				}
			}
			OnPropertyChanged(ValueName);
		}

		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}

		public override bool Value
		{
			get { return _value; }
			set { throw new NotSupportedException(); }
		}
	}
	

}
